<?php

namespace App\Http\Controllers\OpenShop\SiteLocation;

use App\Http\Controllers\BaseController;
use App\Http\Resources\OpenShop\ShopLocation\PlaceHolderSiteLocationResource;
use App\Http\Validate\OpenShop\InvestmentPromotion\PlaceholderValidate;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\OpenShop\SiteLocation\AuthService;
use App\Service\OpenShop\SiteLocation\PlaceHolderSiteLocationService;
use Illuminate\Http\Request;

class PlaceholderController extends BaseController
{
    /**
     * @param Request $request
     * @param $orderNo
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfo(Request $request, $orderNo): \Illuminate\Http\JsonResponse
    {
        $placeholder = new PlaceHolderSiteLocationService($orderNo);
        $authUser    = AuthService::getRmsUserInfo($request);
        $rmsUserId   = $authUser['userId'] ?? 0;

        $isExist = empty($placeholder->getPlaceholderInfo());

        $result      = [
            'formData'          => $isExist ? [] : $placeholder->returnFrontEnd(),
            'approval'          => $placeholder->getAuditHistory(),
            'isShowEditButton'  => !$isExist && $placeholder->checkEditAccess($rmsUserId),
            'isShowAuditButton' => !$isExist && $placeholder->checkAuditAccess($rmsUserId),
        ];

        return $this->success($result);
    }

    /**
     * @param Request $request
     * @param $orderNo
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function save(Request $request, $orderNo): \Illuminate\Http\JsonResponse
    {
        $placeholderInfo               = PlaceholderValidate::updateValidate($request->all());
        (new PlaceHolderSiteLocationService($orderNo))->manageSavePlaceholder($placeholderInfo);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param $orderNo
     * @return \Illuminate\Http\JsonResponse
     */
    public function audit(Request $request, $orderNo): \Illuminate\Http\JsonResponse
    {
        $content = (string)$request->get('content');
        $status  = (int)$request->get('status');

        $authUser = AuthService::getRmsUserInfo($request);

        (new PlaceHolderSiteLocationService($orderNo))->audit($authUser, $status, $content);

        return $this->success();
    }
}
